package modules.majiang.data
{
	import com.netease.protobuf.UInt64;

	import communication.CertManager;
	import communication.hall.HallMsgSender;
	import communication.majiang.MajiangMsgEvent;

	import flash.utils.Dictionary;
	import flash.utils.setTimeout;

	import modules.GameDispatcher;
	import modules.GameEvent;
	import modules.lobby.data.LobbyDataModel;
	import modules.lobby.data.NormalTableModel;
	import modules.majiang.MajiangEvent;

	import protobuf.*;

	import utils.TileTransform;

	/**
	 * @author xumin.xu
	 * 切换桌子管理
	 */
	public class TablesDataManager
	{

		/**
		 * 玩家所在的所有桌子数据
		 */
		[Bindable]
		public static var tableDataModeDic:Dictionary = new Dictionary();

		private static var isInit:Boolean = false;

		private static function get dispatcher():GameDispatcher
		{
			return GameDispatcher.instance;
		}

		public static function init():void
		{
			if (isInit)
				return;


			isInit = true;
		}

		private static function get certManager():CertManager
		{
			return CertManager.getInstance();
		}

		/**
		 * 创建一个桌子
		 */
		public static function createTable(enterTableAck:MSPKG_ENTER_TABLE_ACK):void
		{

			var tableId:UInt64 = enterTableAck.tableId;
			var tableInfo:TABLE_LIVE_INFO = enterTableAck.liveInfo;
			var tableDataModel:TableDataModel = new TableDataModel();
			tableDataModeDic[tableId.toString()] = tableDataModel;
			if (tableInfo.matchId != null)
			{
				tableDataModel.start_time = tableInfo.matchId.startTime;
				tableDataModel.paijuId = tableInfo.matchId.tableId.toString();
			}

			tableDataModel.tableDataFromLobby = LobbyDataModel.cashTableDic[tableId.toString()];

			tableDataModel.chatUIState.canChat = true;
			if (tableInfo.hasCanChat)
			{
				tableDataModel.chatUIState.canChat = tableInfo.canChat;
			}

			if (enterTableAck.tableType == E_TABLE_TYPE.E_TOURNAMENT_TABLE)
			{
				tableDataModel.isTournament = true;
				tableDataModel.tournamentId = enterTableAck.tournmentId;
				tableDataModel.tournamentType = enterTableAck.tournamentType;
				tableDataModel.tableDataFromLobby.tableName = "Tournament" + tableId.toString();
				//如果是锦标赛，请求锦标赛信息
				HallMsgSender.instance.OnRecvTnmtDetailReq(tableDataModel.tournamentId, tableDataModel.tournamentType);
			}

			if (tableDataModel.tableDataFromLobby == null)
			{

				tableDataModel.tableDataFromLobby = new NormalTableModel();
				tableDataModel.tableDataFromLobby.tableID = tableId;
				tableDataModel.tableDataFromLobby.tableName = tableId.toString();

				tableDataModel.tableDataFromLobby.minBlinds = tableInfo.minBlinds;
				tableDataModel.tableDataFromLobby.maxBlinds = tableInfo.maxBlinds;
				tableDataModel.tableDataFromLobby.discardTime = tableInfo.discardTime;
				tableDataModel.tableDataFromLobby.responseTime = tableInfo.responseTime;

				//请求锦标赛当前大小盲注信息
				dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_UPDATE_BLIND_REQ.toString(), {tournamentId: tableDataModel.tournamentId, tableId: tableId}));
			}

			//是否在比赛中
			var isInGame:Boolean = tableInfo.playersInfo.filter(function(element:*, index:int, arr:Array):Boolean
			{
				return element.state == E_PLAYER_STATE.E_PLAYER_STATE_NORMAL;
			}).length > 0;
			if (isInGame)
			{
				tableDataModel.setMatchState(MatchState.INGAME);
			}
			else
			{
				tableDataModel.setMatchState(MatchState.WAIT);
			}

			//在座玩家信息
			tableDataModel.seatedPlayers = [];

			tableDataModel.handTilesNum = TableDataModel.GAME_TYPE_TILE_SEVEN;
			for each (var tablePlayerInfo:TABLE_PLAYER_INFO in tableInfo.playersInfo)
			{
				var tablePlayerDataModel:TablePlayerDataModel = new TablePlayerDataModel();

				tablePlayerDataModel.chairId = tablePlayerInfo.chairId;
				tablePlayerDataModel.userName = certManager.convertByteArrayToString(tablePlayerInfo.playerName);

				tablePlayerDataModel.avatarId = tablePlayerInfo.avatarId;

				//本房间内的剩余赌注
				tablePlayerDataModel.money = tablePlayerInfo.money;

				//本局玩家总下注金额
				tableDataModel.totalBetInGame[tablePlayerDataModel.chairId - 1] = tablePlayerInfo.hasTotalBet ? tablePlayerInfo.totalBet : 0;

				tableDataModel.playerTiles[tablePlayerDataModel.chairId] = TileTransform.arrServerToClient(tablePlayerInfo.tiles);

				//玩家手上牌的数量
				tableDataModel.playerTiles[tablePlayerDataModel.chairId].length = tablePlayerInfo.tilesNum;

				if (tablePlayerInfo.tilesNum > 0 && tablePlayerInfo.tilesNum < 7)
				{
					tableDataModel.handTilesNum = TableDataModel.GAME_TYPE_TILE_FOUR;
				}

				//设置该玩家的状态
				switch (tablePlayerInfo.state)
				{
					case E_PLAYER_STATE.E_PLAYER_STATE_NORMAL:
						tableDataModel.inMatchPlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
						break;
					case E_PLAYER_STATE.E_PLYAER_STATE_WIN:
						tableDataModel.winPlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
						break;
					case E_PLAYER_STATE.E_PLYAER_STATE_LOSE:
						tableDataModel.losePlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
						break;
					case E_PLAYER_STATE.E_PLYAER_STATE_FOLD:
						tableDataModel.foldPlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
						break;
					case E_PLAYER_STATE.E_PLYAER_STATE_SIT:

						break;
					case E_PLAYER_STATE.E_PLAYER_STATE_SITOUT:
						tableDataModel.sitOutPlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
						break;
				}

				if (tablePlayerInfo.isSitout == true && tableDataModel.isSitout(tablePlayerInfo.chairId) == false)
				{
					tableDataModel.sitOutPlayerList.push({timer: 1, chairId: tablePlayerDataModel.chairId});
				}

				tableDataModel.seatedPlayers[tablePlayerDataModel.chairId.toString()] = tablePlayerDataModel;

				//判断该玩家是否是自己
				if (GlobalData.username == tablePlayerDataModel.userName)
				{
					tableDataModel.sitChairId = tablePlayerDataModel.chairId;
					tableDataModel.lookChairId = tableDataModel.sitChairId;

					//买入余额
					tableDataModel.money = tablePlayerDataModel.money;
				}
			}

			//手牌
			tableDataModel.tilesInHand = TileTransform.arrServerToClient(tableInfo.tilesInHand);
			//如果自己没有坐下，则不可能有手牌
			if (tableDataModel.sitChairId < 0)
			{
				tableDataModel.tilesInHand = [];
			}
			else
			{
				//给牌排序
				tableDataModel.tilesInHand.sort(TileTransform.sortOnClientTile);
			}

			//桌子上的牌
			tableDataModel.tilesOnTable = TileTransform.arrServerToClient(tableInfo.tilesOnTable);

			//庄家座位号
			tableDataModel.bankerId = tableInfo.bankerChairId;

			//创建桌面上剩余牌堆数据
			tableDataModel.restCardData = new RestCardData(tableDataModel);
			tableDataModel.restCardData.restMajiangNum = tableInfo.tilesWallCount;

			//奖池信息
			tableDataModel.bonusPotsData = new BonusPotsData(tableDataModel);
			tableDataModel.bonusPotsData.betPoolNtf = tableInfo.betPoolNtf;

			//更新麻将桌子界面中显示
			dispatcher.dispatchEvent(new MajiangEvent(MajiangEvent.UPDATE_MAJIANG_TABLE_VIEW, {tableId: tableId}));

			dispatcher.dispatchEvent(new GameEvent(GameEvent.ENTERED_TABLE, {tableIdStr: tableId.toString()}));

		}

		/**
		 * 离开桌子
		 * @param tableIdStr 桌子编号，字符串表示
		 */
		public static function leaveTable(tableIdStr:String):void
		{
			dispatcher.dispatchEvent(new GameEvent(GameEvent.LEAVE_TABLE, {tableIdStr: tableIdStr}));
			
			//抛出事件后有人要用这个数据,所以过一会再清除
			setTimeout(function():void
			{
				if (tableDataModeDic[tableIdStr])
				{
					if (UIAllRefer.instance.mGameUiDic[tableIdStr]) //删除UI
					{
						UIAllRefer.instance.mGameUiDic[tableIdStr] = null;
						delete UIAllRefer.instance.mGameUiDic[tableIdStr];
					}
					tableDataModeDic[tableIdStr] = null; //删除数据
					delete tableDataModeDic[tableIdStr];
				}
			}, 10);
		}

		/**
		 * 判断是否已经加入了该桌子
		 */
		public static function isJoined(tableId:UInt64):Boolean
		{
			return tableDataModeDic[tableId.toString()] ? true : false;
		}

		/**
		 * 获取进入桌子个数
		 */
		public static function getEnterTableNum():int
		{
			var num:int = 0;
			for (var key:String in tableDataModeDic)
			{
				num++;
			}
			return num;
		}
	}
}
